<!--
 * @Author: 可以清心
 * @Description: 
 * @Date: 2022-11-24 14:40:56
 * @LastEditTime: 2023-03-07 13:45:31
-->
<template>
    <div class="login">
        <el-form ref="loginForm" :model="form" :rules="rules">
            <el-form-item prop="account">
                <el-input v-model="form.account" placeholder="员工账号"></el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input placeholder="员工密码" v-model="form.password" show-password></el-input>
            </el-form-item>
            <el-form-item style="margin-bottom: 12px;">
                <el-button class="login-button" type="primary" @click="handleLogin"><i :class="className"></i>登录</el-button>
            </el-form-item>
        </el-form>
        <div class="bottom">
            <el-checkbox v-model="checked">记住密码</el-checkbox>
            <a :href="forgetHref" class="forget" target="_blank">忘记密码?</a>
        </div>
    </div>
</template>

<script>
import axios from 'axios'
import encryption from '@/utils/encryption.util'
import storage from '@/utils/storage'
export default {
    name: 'JdfLogin',
    data(){
        return {
            form: {
                account: '',
                password: ''
            },
            className: '',
            checked: '',
            rules: {
                account: [
                    {
                        validator: function(rule, value, callback){
                            if (!value) {
                                return callback(new Error('账号不能为空!'));
                            }else{
                                callback();
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                password: [
                    {
                        validator: function(rule, value, callback){
                            if (!value) {
                                return callback(new Error('密码不能为空!'));
                            }else{
                                callback();
                            }
                        },
                        trigger: 'blur'
                    }
                ]
            },
            forgetHref: ''
        }
    },
    created(){
        // console.log(storage)
        this.loadUserInfo();
        this.forgetHref = this.getForgetPasswordUrl();
    },
    mounted(){
        
    },
    methods: {
        /**
         * @description: 点击登录
         * @return {void | boolean}
         */        
        handleLogin(){
            this.$refs.loginForm.validate((valid) => {
                if (valid) {
                    this.className = 'el-icon-loading'
                    // this.encryptionPassWord();
                    this.userCenterLogin();
                } else {
                    return false;
                }
            })
        },
        /**
         * @description: 接入用户中心的登录方式
         * @return {void}
         */        
        async userCenterLogin(){
            const {getUserCenterAppIdAndUrl, checked} = this;
            const {account, password} = this.form;

            let encyptionPass = await encryption.passwordEncryption(password);

            let {userCenterAppId, userCenterLoginUrl} = getUserCenterAppIdAndUrl();
            
            if(userCenterAppId && userCenterLoginUrl){
                axios({
                    url: userCenterLoginUrl,
                    method: 'post',
                    data: {
                        password: encyptionPass,
                        userName: account,
                        appId: userCenterAppId
                    }
                }).then((resp) => {
                    this.className = '';
                    const res = resp.data;
                    if(res.code === 'ok'){
                        const {setStorage, setModule, removeStorage} = storage;
                        if(checked){
                            // 记住密码
                            setStorage(account, 'username');
                            setStorage(password, 'password');
                        }else{
                            removeStorage();
                        }
                        const {data} = res;

                        setModule(data);

                        if(location.hostname !== 'localhost'){
                            window.open(location.origin + '/workbench/' + data.tenantId + '/workbench', '_self')
                        }
                    }else{
                        if(res.code === 'warning'){
                            this.$message({
                                message: res.message,
                                type: 'warning'
                            });
                            this.$router.push({path: '/417'})
                        }else{
                            this.$message.error(res.message)
                        }
                        // this.$message.error('登录失败，请检查账号密码！')
                    }
                }).catch((error) => {
                    // this.$router.push({path: '/417'})
                    this.$message.error(error?.response?.data?.message)
                })
            }else{
                this.className = '';
                this.$message.error('未配置环境变量接口，请检查环境变量是否配置完整');
            }
        },
        /**
         * @description: 登录接口
         * @return {void}
         * @deprecated 弃用改用用户中心登录接口
         */        
        async encryptionPassWord(){
            const {getApplicationInfo, checked} = this;
            const {account, password} = this.form;
            let encyptionPass = await encryption.passwordEncryption(password);
            let applicationInfo = getApplicationInfo();

            let domain = applicationInfo.domain || location.host;

            let url = '';

            if(location.hostname !== 'localhost'){
                url = domain + '/xdap-admin/user/login'
            }else{
                url = 'http://172.19.11.93:8091/xdap-admin/user/login'
            }

            axios({
                url,
                method: 'post',
                data: {
                    type: "account",
                    securityCode: '',
                    password: encyptionPass,
                    account,
                    loginType: 'WORKBENCH'
                }
            }).then((resp) => {
                this.className = '';
                const res = resp.data;
                if(res.code === 'ok'){
                    const {setStorage, setModule, removeStorage} = storage;
                    if(checked){
                        // 记住密码
                        setStorage(account, 'username');
                        setStorage(password, 'password');
                    }else{
                        removeStorage();
                    }
                    const {data} = res;

                    setModule(data);

                    if(location.hostname !== 'localhost'){
                        window.open(location.origin + '/workbench/' + data.userDefaultTenant.id + '/workbench', '_self')
                    }
                }else{
                    this.$message.error('登录失败，请检查账号密码！')
                }
            }).catch(() => {
                this.$router.push({path: '/417'})
            })
        },
        /**
         * @description: 获取应用信息
         * @return {any}
         */        
        getApplicationInfo(){
            let GLOBAL_ENV = window.GLOBAL_ENV;
        
            if(GLOBAL_ENV){
                return {
                    domain: GLOBAL_ENV['VUE_APP_BASE_DOMAIN'],
                }
            }

            return {}
        },
        /**
         * @description: 获取忘记密码链接的地址
         * @return {string}
         */        
        getForgetPasswordUrl(){
            let GLOBAL_ENV = window.GLOBAL_ENV;
            let forgetUrl = GLOBAL_ENV['VUE_APP_FORGET_URL'];

            return forgetUrl || 'http://user-dev.boe.com.cn/static/forgetPassword/index.html';
        },
        /**
         * @description: 加载用户保存的信息
         * @return {void}
         */        
        loadUserInfo(){
            const {getUsername, getPassWord} = storage;
            let account = getUsername();
            let password = getPassWord();

            if(account){
                this.form.account = atob(account);
            }

            if(password){
                this.form.password = atob(password);
            }

            if(account && password){
                this.checked = true;
            }
        },
        /**
         * @description: 获取用户中心提供的appId
         * @return {void}
         */        
        getUserCenterAppIdAndUrl(){
            let GLOBAL_ENV = window.GLOBAL_ENV;
        
            if(GLOBAL_ENV){
                return {
                    userCenterAppId: GLOBAL_ENV['BOE_USER_CENTER_APP_ID'],
                    userCenterLoginUrl: GLOBAL_ENV['BOE_USER_CENTER_LOGIN_URL']
                };
            }

            return {}
        }
    }
}

</script>

<style lang="less">
.login {
    .login-button{
        width: 100%;
        background: #005EBA;
        border-radius: 2px;
        color: #fff;
        font-size: 14px;
        font-family: FZLTHJW--GB1-0;
        letter-spacing: 1em;
        .el-icon-loading{
            margin-right: 1em;
            letter-spacing: 0;
        }
    }

    .bottom{
        .el-checkbox__label{
            color: #005EBA;
            // font-weight: 100;
        }
        font-size: 14px;
        // font-weight: 100;

        .forget{
            float: right;
            text-decoration: none;
            color: #005EBA;
        }
    }
}
</style>